<template>
  <div class="mod-course">
    <el-form
      :inline="true"
      :model="dataForm"
    >
      <el-form-item>
        <el-input
          v-model="dataForm.title"
          placeholder="课程标题"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="dataForm.categoryId"
          placeholder="课程分类"
          clearable
        >
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.categoryName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="dataForm.status"
          placeholder="课程状态"
          clearable
        >
          <el-option
            label="草稿"
            :value="0"
          />
          <el-option
            label="已发布"
            :value="1"
          />
          <el-option
            label="已下架"
            :value="2"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="() => { page.currentPage = 1; getDataList() }"
        >
          查询
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="onAddOrUpdate()"
        >
          新增
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      row-key="id"
      style="width: 100%; margin-bottom: 20px;"
      v-loading="dataListLoading"
    >
      <el-table-column
        prop="title"
        header-align="center"
        align="center"
        width="200"
        label="课程标题"
      />
      <el-table-column
        prop="coverImage"
        header-align="center"
        align="center"
        width="120"
        label="课程封面"
      >
        <template #default="scope">
          <img
            alt=""
            :src="scope.row.coverImage"
            style="height: 80px; width: 120px;"
          >
        </template>
      </el-table-column>
      <el-table-column
        prop="categoryId"
        header-align="center"
        align="center"
        width="120"
        label="分类"
      >
        <template #default="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="currentPrice"
        header-align="center"
        align="center"
        width="100"
        label="价格"
      />
      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        width="100"
        label="状态"
      >
        <template #default="scope">
          <el-tag
            v-if="scope.row.status === 0"
            type="info"
          >
            草稿
          </el-tag>
          <el-tag
            v-else-if="scope.row.status === 1"
            type="success"
          >
            已发布
          </el-tag>
          <el-tag
            v-else
            type="danger"
          >
            已下架
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="studyCount"
        header-align="center"
        align="center"
        width="100"
        label="学习人数"
      />
      <el-table-column
        prop="isHot"
        header-align="center"
        align="center"
        width="100"
        label="热门状态"
      >
        <template #default="scope">
          <el-tag
            v-if="scope.row.isHot === 1"
            type="success"
          >
            热门
          </el-tag>
          <el-tag
            v-else
            type="info"
          >
            普通
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        width="450"
        label="操作"
      >
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 1"
            type="primary"
            size="small"
            @click="onAddOrUpdate(scope.row.id, true)"
          >
            查看
          </el-button>
          <el-button
            v-else
            type="primary"
            size="small"
            @click="onAddOrUpdate(scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-if="scope.row.status === 0 || scope.row.status === 2"
            type="success"
            size="small"
            @click="onPublish(scope.row.id)"
          >
            发布
          </el-button>
          <el-button
            v-if="scope.row.status === 1"
            type="warning"
            size="small"
            @click="onOffline(scope.row.id)"
          >
            下架
          </el-button>
          <el-button
            v-if="scope.row.status === 0"
            type="danger"
            size="small"
            @click="onDelete(scope.row.id)"
          >
            删除
          </el-button>
          <el-button
            v-if="scope.row.isHot === 1"
            type="info"
            size="small"
            @click="onSetHot(scope.row.id, 0)"
          >
            取消热门
          </el-button>
          <el-button
            v-else
            type="success"
            size="small"
            @click="onSetHot(scope.row.id, 1)"
          >
            设为热门
          </el-button>
          <el-button
            type="info"
            size="small"
            @click="onViewComments(scope.row.id)"
          >
            查看评价
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      :current-page="page.currentPage"
      :page-size="page.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="page.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
    />
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      :category-list="categoryList"
      @refresh-data-list="getDataList"
      @close="addOrUpdateVisible=false"
    />
    <!-- 弹窗, 课程评价 -->
    <course-comment-dialog
      v-if="commentDialogVisible"
      ref="commentDialogRef"
      @close="commentDialogVisible=false"
    />
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import AddOrUpdate from './add-or-update.vue'
import CourseCommentDialog from './course-comment-dialog.vue'

const dataForm = ref({
  title: '',
  categoryId: '',
  status: ''
})

const page = reactive({
  total: 0, // 总条数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})

onMounted(() => {
  getCategoryList()
  getDataList()
})

const dataList = ref([])
const dataListLoading = ref(false)
const categoryList = ref([])

/**
 * 获取分类列表
 */
const getCategoryList = () => {
  http({
    url: http.adornUrl('/admin/courseCategory/page'),
    method: 'get',
    params: http.adornParams()
  })
    .then(({ data }) => {
      categoryList.value = data.records
    })
}

/**
 * 获取分类名称
 */
const getCategoryName = (categoryId) => {
  const category = categoryList.value.find(item => item.id === categoryId)
  return category ? category.categoryName : '-'
}

/**
 * 获取数据列表
 */
const getDataList = () => {
  dataListLoading.value = true
  http({
    url: http.adornUrl('/admin/course/page'),
    method: 'get',
    params: http.adornParams({
      title: dataForm.value.title,
      categoryId: dataForm.value.categoryId,
      status: dataForm.value.status,
      current: page.currentPage,
      size: page.pageSize
    })
  })
    .then(({ data }) => {
      dataList.value = data.records
      page.total = data.total
      dataListLoading.value = false
    })
}

/**
 * 每页数量变化
 */
const sizeChangeHandle = (val) => {
  page.pageSize = val
  page.currentPage = 1
  getDataList()
}

/**
 * 当前页变化
 */
const currentChangeHandle = (val) => {
  page.currentPage = val
  getDataList()
}

const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref(null)

const commentDialogVisible = ref(false)
const commentDialogRef = ref(null)

/**
 * 新增 / 修改
 * @param id
 * @param isReadOnly 是否为只读模式（已发布课程只能查看）
 */
const onAddOrUpdate = (id, isReadOnly = false) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id, isReadOnly)
  })
}

/**
 * 发布课程
 */
const onPublish = (id) => {
  ElMessageBox.confirm('确定发布该课程?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      http({
        url: http.adornUrl(`/admin/course/publish/${id}`),
        method: 'post'
      })
        .then(() => {
          ElMessage({
            message: '发布成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              page.currentPage = 1
              getDataList()
            }
          })
        })
    })
}

/**
 * 下架课程
 */
const onOffline = (id) => {
  ElMessageBox.confirm('确定下架该课程?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      http({
        url: http.adornUrl(`/admin/course/offline/${id}`),
        method: 'post'
      })
        .then(() => {
          ElMessage({
            message: '下架成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              page.currentPage = 1
              getDataList()
            }
          })
        })
    })
}

/**
 * 删除课程
 * @param id
 */
const onDelete = (id) => {
  ElMessageBox.confirm('确定删除该课程?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      http({
        url: http.adornUrl(`/admin/course/del/${id}`),
        method: 'post'
      })
        .then(() => {
          ElMessage({
            message: '删除成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              page.currentPage = 1
              getDataList()
            }
          })
        })
    })
}

/**
 * 设置课程热门状态
 * @param id 课程ID
 * @param isHot 热门状态（0:否,1:是）
 */
const onSetHot = (id, isHot) => {
  const message = isHot === 1 ? '确定设置该课程为热门?' : '确定取消该课程的热门状态?'
  ElMessageBox.confirm(message, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      http({
        url: http.adornUrl(`/admin/course/setHot/${id}/${isHot}`),
        method: 'post'
      })
        .then(() => {
          ElMessage({
            message: isHot === 1 ? '设置为热门成功' : '取消热门成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              page.currentPage = 1
              getDataList()
            }
          })
        })
    })
}

/**
 * 查看课程评价
 * @param id 课程ID
 */
const onViewComments = (id) => {
  commentDialogVisible.value = true
  nextTick(() => {
    commentDialogRef.value?.init(id)
  })
}
</script>

<style lang="scss" scoped>
.mod-course {
  img {
    height: 80px;
    width: 120px;
  }
}
</style>
